/*
  Tank  with ESP32: WIFI
     ssid = "tank";
     password = "12345678";
     http://192.168.4.1/
*/
#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiAP.h>
#include <WebServer.h>
#include "component_btn7919.h"
#include "component_servo.h"
// #include "component_led.h"

// Set these to your desired credentials.
const char *ssid = "tank";
const char *password = "12345678";

WebServer server(80);

const char webpage[] PROGMEM = R"=====(
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
   html { font-family: sans-serif; display: inline-block; margin: 0px auto; text-align: center;}
   .button { background-color: #195B6A; border: none; color: white; padding: 3px 10px;
            width:150px; height: 30px;text-decoration: none; font-size: 18px; margin: 2px; cursor: pointer;}
   .swbutton { background-color: #195B6A; border: none; color: white; padding: 3px 10px;
            width:100px; height: 30px;text-decoration: none; font-size: 18px; margin: 2px; cursor: pointer;}
   .btn_circle {background-color: #195B6A; width:60px; height: 60px; border-radius: 50%; color: red; font-size: 18px; cursor: pointer;}         
</style>
</head>
<title>The Tracked Vehicle</title>
<body>
<h2 align=center>The Tracked Vehicle</h2>
<p><button class="button" onclick="send('FORWARD')">Go</button></p>
<p><button class="swbutton" onclick="send('LEFT_FORWARD')">L <- (0)</button>&ensp;
   <button class="btn_circle" onclick="send('STOP')">STOP</button>&ensp;
   <button class="swbutton" onclick="send('RIGHT_FORWARD')">R -> (0)</button></p>
<p><button class="button" onclick="send('BACKWARD')">BACK</button></p>
<p><button class="button" onclick="send('LEFT_STEP')">sL <-</button>&ensp;&ensp;
<button class="button" onclick="send('RIGHT_STEP')">sR -> </button></p>
<p><button class="button" onclick="send('LEFT_SPIN')">LS <- (s)</button>&ensp;&ensp;
<button class="button" onclick="send('RIGHT_SPIN')">RS -> (s)</button></p>

<h3>Left:<span id="left_speed_pwm_val">0</span> &ensp;&ensp;
                 Right:<span id="right_speed_pwm_val">0</span></h3>

<p><button class="button" onclick="send('SPEED_UP')">Speed +</button>&ensp;&ensp;
   <button class="button" onclick="send('SPEED_DOWN')">Speed -</button>
</p>
<p><button class="button" onclick="send('LEFT_SPEED_UP')">Left +</button>&ensp;&ensp;
   <button class="button" onclick="send('RIGHT_SPEED_UP')">Right +</button>
</p>
<p><button class="button" onclick="send('LEFT_SPEED_DOWN')">Left -</button>&ensp;&ensp;
   <button class="button" onclick="send('RIGHT_SPEED_DOWN')">Right -</button>
</p>
<p><button class="swbutton" onclick="send('SERVO_CLOCKWISE')">Srv Clock</button>&ensp;
   <button class="swbutton" onclick="send('SERVO_CENTER')">Center</button>&ensp;
   <button class="swbutton" onclick="send('SERVO_ANTI_CLOCKWISE')">Srv AntiC</button>
 </p>
<div>
  <h3>Distance(cm): <span id="distance">0</span></h3>
  <h4>T:<span id="temperature_val">0</span> &ensp;&ensp;
                 H:<span id="humidity_val">0</span></h4>
  <h3>State: <span id="state">STOP</span> </h3>
</div>
<script>
function send(robot_cmd) 
{
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("state").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "robot_set?state="+robot_cmd, true);
  xhttp.send();
}

setInterval(function() 
{
  getData();
}, 1000); 

function getData() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var dataobj=JSON.parse(this.responseText);
      document.getElementById("distance").innerHTML = dataobj.distance;
      document.getElementById("left_speed_pwm_val").innerHTML = dataobj.left_speed_pwm;
      document.getElementById("right_speed_pwm_val").innerHTML = dataobj.right_speed_pwm;
      document.getElementById("temperature_val").innerHTML = dataobj.temperature;
      document.getElementById("humidity_val").innerHTML = dataobj.humidity;
    }
  };
  xhttp.open("GET", "data_read", true);
  xhttp.send();
}
</script>
</body>
</html>
)=====";

void webclient_cmd(String robot_cmd) {
  ROBOT_ACTION_CODE cur_cmd = car_state;
  if (robot_cmd.equalsIgnoreCase("FORWARD")) {
    cur_cmd = ROBOT_FORWARD;
  } else if (robot_cmd.equalsIgnoreCase("BACKWARD")) {
    cur_cmd = ROBOT_BACKWARD;
  } else if (robot_cmd.equalsIgnoreCase("STOP")) {
    cur_cmd = ROBOT_STOP;
  } else if (robot_cmd.equalsIgnoreCase("LEFT_FORWARD")) {
    cur_cmd = ROBOT_LEFT_FORWARD;
  } else if (robot_cmd.equalsIgnoreCase("RIGHT_FORWARD")) {
    cur_cmd = ROBOT_RIGHT_FORWARD;
  } else if (robot_cmd.equalsIgnoreCase("LEFT_STEP")) {
    cur_cmd = ROBOT_LEFT_STEP;
  } else if (robot_cmd.equalsIgnoreCase("RIGHT_STEP")) {
    cur_cmd = ROBOT_RIGHT_STEP;
  } else if (robot_cmd.equalsIgnoreCase("LEFT_SPIN")) {
    cur_cmd = ROBOT_LEFT_SPIN;
  } else if (robot_cmd.equalsIgnoreCase("RIGHT_SPIN")) {
    cur_cmd = ROBOT_RIGHT_SPIN;
  } else if (robot_cmd.equalsIgnoreCase("SPEED_UP")) {
    cur_cmd = ROBOT_SPEED_UP;
  } else if (robot_cmd.equalsIgnoreCase("SPEED_DOWN")) {
    cur_cmd = ROBOT_SPEED_DOWN;
  } else if (robot_cmd.equalsIgnoreCase("LEFT_SPEED_UP")) {
    cur_cmd = ROBOT_LEFT_SPEED_UP;
  } else if (robot_cmd.equalsIgnoreCase("LEFT_SPEED_DOWN")) {
    cur_cmd = ROBOT_LEFT_SPEED_DOWN;
  } else if (robot_cmd.equalsIgnoreCase("RIGHT_SPEED_UP")) {
    cur_cmd = ROBOT_RIGHT_SPEED_UP;
  } else if (robot_cmd.equalsIgnoreCase("RIGHT_SPEED_DOWN")) {
    cur_cmd = ROBOT_RIGHT_SPEED_DOWN;
  } else if (robot_cmd.equalsIgnoreCase("SERVO_CLOCKWISE")) {
    ultrasonic_servo_action(SERVO_CLOCKWISE);
  } else if (robot_cmd.equalsIgnoreCase("SERVO_ANTI_CLOCKWISE")) {
    ultrasonic_servo_action(SERVO_ANTI_CLOCKWISE);
  } else if (robot_cmd.equalsIgnoreCase("SERVO_CENTER")) {
    ultrasonic_servo_action(SERVO_CENTER);
  };
  if (cur_cmd != car_state) {
    car_action(cur_cmd);
    // led_action(cur_cmd);
  }
}

void handleRoot() {
  String s = webpage;
  server.send(200, "text/html", s);
}

void handleRobot() {
  String robot_cmd = server.arg("state");
  Serial.println(robot_cmd);
  server.send(200, "text/plane", robot_cmd);
  webclient_cmd(robot_cmd);
}

void handleSensor() {
  if (data_ready) {
    server.send(200, "text/json", json);
  } else {
    server.send(503, "text/plane", "none data");
  }
}

void setup_wifi() {
  Serial.println();
  Serial.println("Configuring access point...");
  // You can remove the password parameter if you want the AP to be open.
  // a valid password must have more than 7 characters
  if (!WiFi.softAP(ssid, password)) {
    log_e("Soft AP creation failed.");
    while (1)
      ;
  }

  IPAddress myIP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(myIP);

  server.on("/", handleRoot);
  server.on("/robot_set", handleRobot);
  server.on("/data_read", handleSensor);
  server.begin();
  Serial.println("Server started");
}

void loop_wifi() {
  server.handleClient();
}
